# -*- coding: utf-8 -*-


from openerp import models
from openerp.osv import osv, fields, orm
from openerp import SUPERUSER_ID

#增加users表中添加委托给字段
class res_users_ext(orm.Model):
    '''人力资源部门创建销售员时可以把其他销售员的客户委托给新销售员'''
    _inherit = 'res.users'
    _columns = {
        'share_to': fields.many2many('res.users', 'user_user_rel', 'source_id', 'dest_id', string=u'委托给'),
        }

    def __init__(self, pool, cr):
        init_res = super(res_users_ext, self).__init__(pool, cr)
        self.SELF_WRITEABLE_FIELDS = list(self.SELF_WRITEABLE_FIELDS)
        self.SELF_WRITEABLE_FIELDS.extend(['share_to'])
        return init_res

    def judge_fields_is_group(self,cr,uid,ids,vals,groups,context=None):
        res = {}
        model_data_obj = self.pool.get('ir.model.data')
        group_id_dict = {model_data_obj.xmlid_to_res_id(
            cr, SUPERUSER_ID, group):group for group in groups}
        for key in vals.keys():
            if key.find('in_group')>=0:
                str_list = key.split('_')
                if int(str_list[2]) in group_id_dict.keys():
                    res[group_id_dict.get(int(str_list[2]))] = vals.get(key)
        return res

    def write(self,cr,uid,ids,vals,context=None):
        group_vals = self.judge_fields_is_group(cr, uid, ids, vals, ['dzx_ext.group_stores', 'dzx_ext.group_agents'],
                                                context=context)
        model_data_obj = self.pool.get('ir.model.data')

        for user in self.browse(cr, uid, ids, context=context):
            if group_vals.get('dzx_ext.group_stores','default_vals')!='default_vals':
                user.partner_id.write({'is_stores': True})
            if group_vals.get('dzx_ext.group_agents','default_vals')!='default_vals':
                user.partner_id.write({'is_agents': True})
            if not group_vals.get('dzx_ext.group_stores') and group_vals.get('dzx_ext.group_stores','default_vals') != 'default_vals':
                user.partner_id.write({'is_stores': False})
                group_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'dzx_ext.group_stores')
                del vals['in_group_%s'%(group_id)]
            if not group_vals.get('dzx_ext.group_agents') and group_vals.get('dzx_ext.group_agents','default_vals') != 'default_vals':
                group_id = model_data_obj.xmlid_to_res_id(cr, SUPERUSER_ID, 'dzx_ext.group_agents')
                del vals['in_group_%s' % (group_id)]
                user.partner_id.write({'is_agents': False})
        return_vals = super(res_users_ext,self).write(cr,uid,ids,vals,context=context)

        return return_vals